<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>px转cm</title>
</head>

<body>
    <div style="width: 1cm; height: 1cm;background-color: red;"></div>
    <div id="div"></div>
    <script>
        //获取PPI
        function getPPI() {
            var PPI = new Array();
            if (window.screen.deviceXDPI != undefined) {
                PPI[0] = window.screen.deviceXDPI;
                PPI[1] = window.screen.deviceYDPI;
            } else {
                var tmpNode = document.createElement("DIV");
                tmpNode.style.cssText = "width:1in;height:1in;position:absolute;left:0px;top:0px;z-index:99;visibility:hidden";
                document.body.appendChild(tmpNode);
                PPI[0] = parseInt(tmpNode.offsetWidth);
                PPI[1] = parseInt(tmpNode.offsetHeight);
                tmpNode.parentNode.removeChild(tmpNode);
            }
            return PPI;
        }
        const ppi = getPPI();


        const px = ppi[0] / 2.54 * 1;

        const div = document.querySelector('#div');
        div.style = `width:${px}px;height:${px}px;background-color: green`;
    </script>
</body>

</html>